package com.example.demo.controller;


import com.example.demo.identity.Group;
import com.example.demo.mapper.GroupMapper;
import com.example.demo.identity.PullGroupInfo;
import com.example.demo.services.MongoService;
import com.example.demo.utils.ResponseMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/group")
public class GroupController {

    //    图片链接数组
    private static final String[] IMAGE_LINKS = {
            "https://free.picui.cn/free/2025/08/02/688dac1c115cc.jpeg", "https://free.picui.cn/free/2025/08/02/688daa3b2d85f.jpeg", "https://free.picui.cn/free/2025/08/02/688daa3b02efd.jpeg",
            "https://free.picui.cn/free/2025/08/02/688daa3856fca.jpeg", "https://free.picui.cn/free/2025/08/02/688daa36ef6eb.jpeg", "https://free.picui.cn/free/2025/08/02/688daa36e9113.jpeg",
            "https://free.picui.cn/free/2025/08/02/688daa39e121b.jpeg", "https://free.picui.cn/free/2025/08/02/688daa36c6109.jpeg", "https://free.picui.cn/free/2025/08/02/688daa39a0126.jpeg",
            "https://free.picui.cn/free/2025/08/02/688daa34bbf77.jpeg", "https://free.picui.cn/free/2025/08/02/688daa3968254.jpeg", "https://free.picui.cn/free/2025/08/02/688daa34a0da8.jpeg",
            "https://free.picui.cn/free/2025/08/02/688daa38a1dde.jpeg", "https://free.picui.cn/free/2025/08/02/688daa3481a26.jpeg", "https://free.picui.cn/free/2025/08/02/688daa343a027.jpeg",
            "https://free.picui.cn/free/2025/08/02/688daa31b3aed.jpeg", "https://free.picui.cn/free/2025/08/02/688daa31b0657.jpeg", "https://free.picui.cn/free/2025/08/02/688daa317fce6.jpeg",
            "https://free.picui.cn/free/2025/08/02/688daa3150f8c.jpeg", "https://free.picui.cn/free/2025/08/02/688daa3126b20.jpeg"
    };

    private static final Logger logger = LoggerFactory.getLogger(GroupController.class);
    private final GroupMapper groupMapper;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public GroupController(GroupMapper groupMapper) {
        this.groupMapper = groupMapper;
    }

    @Autowired
    private MongoService mongoService;

    @Autowired
    private ObjectMapper objectMapper;

//    创建群聊接口

    /**
     * @return
     * @Param leaderId  群主Id，顾名思义就是当前用户Id
     */
    @PostMapping("/create-group/{leaderId}")        // 在这个接口中尝试使用矩阵变量来传递参数（因为定义的实体类不符合，处理起来太麻烦（个人懒得处理））
//    这里的pathVar属性其实也可以省略
    public ResponseEntity<Map<String, Object>> createGroup(@PathVariable("leaderId") String leaderId,
                                                           @RequestParam("pullGroupInfo") String pullGroupInfo) throws Exception {
        ResponseMessage message = new ResponseMessage();

        try {
//            将JSON字符串转换为对象，方便后期使用
            PullGroupInfo pullInfo = objectMapper.readValue(pullGroupInfo, PullGroupInfo.class);
            List<Group> groupList = groupMapper.findGroupByGroupId(leaderId);
            if (groupList.isEmpty()) {
                // 将群聊基本信息存储在Group对象中
                String imageLinks = getRandomImageLinks();
                Group group = Group.builder()
                        .group_name(pullInfo.getGroup_name()).group_type(pullInfo.getGroup_type()).group_id(pullInfo.getGroup_id())
                        .group_leader(pullInfo.getGroup_leader()).group_avatar(imageLinks).create_at(Timestamp.valueOf(LocalDateTime.now().format(DATE_TIME_FORMATTER))).build();
//                更新操作
                int createResult = groupMapper.createGroup(group);
                if (createResult == 1) {
//                    在这里存储群成员信息
//                    序列化为JSON字符串
                    String jsonString = objectMapper.writeValueAsString(pullInfo.getGroup_members());
                    mongoService.addDocument(group.getGroup_id(), jsonString, group);
                    return message.responseMessage("群聊创建成功", HttpStatus.OK);
                } else {
//                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                    return message.responseMessage("群聊创建失败，未知的信息，联系管理员解决问题！", HttpStatus.INTERNAL_SERVER_ERROR);
                }
            } else {
//                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("重复的群聊信息");
                return message.responseMessage("存在重复的群聊信息", HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //    查询群成员信息的接口（等同于获取群聊的at列表）
    @GetMapping("/get-only-group-chat-members/{groupId}")
    public ResponseEntity<List<PullGroupInfo.MembersInfo>> getGroupMembers(@PathVariable("groupId") String groupId) {
        List<PullGroupInfo.MembersInfo> result = mongoService.getGroupMembersOnly(groupId);
        if (!result.isEmpty()) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    //    通过userId获取用户群聊信息
    @GetMapping("/get-user-belongs-chat-groups/{userId}")
    public ResponseEntity<?> getBelongsGroup(@PathVariable("userId") String userId) throws Exception {
        ResponseMessage message = new ResponseMessage();
        Map<String, Object> resultMap = new HashMap<>();
//        存储群消息
        List<Group> groupList = new ArrayList<>();
//        获取Ids
        List<Object> idList = mongoService.getGroupIdsByUserId(userId);
        if (idList.isEmpty()) {
            resultMap.put("message", "未找到群组消息");
            resultMap.put("data", groupList);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(resultMap);
        }
        for (Object id : idList) {
            List<Group> result = groupMapper.findGroupByGroupId(String.valueOf(id));
            if (result != null && !result.isEmpty()) {
                groupList.add(result.get(0));
            }
        }
        resultMap.put("message", "信息获取成功");
        resultMap.put("data", groupList);
        return ResponseEntity.status(HttpStatus.OK).body(resultMap);
    }


    /*   工具方法    */
//    获取随机群聊链接
    private String getRandomImageLinks() {
        Random random = new Random();
//        随机获取一个索引
        int randomIndex = random.nextInt(IMAGE_LINKS.length);
//        返回随机索引对应的图片链接
        return IMAGE_LINKS[randomIndex];
    }

}
